function avg(a, b) {
  var res = parseInt((a / b) * 100) / 100; //保留两位、三位小数 同理
  return res;
}

function changeMainAccount(account) {
  $.ajax({
    url: ajaxWebsite + 'Home/Ytc/changeMainAccount',
    type: 'POST',
    data: {
      account: account
    },
    success: function (res) {
      var MainAccount = res
      $('#from').val(MainAccount)
      var account = $('#from').val()
      getTotalAmount(account)
      ipcRenderer.send('window-reload')
    }
  })
}

function getAllAccount(code, loginAccount) {
  addToast('请稍后', '正在查询中…', 'notice')
  $.ajax({
    url: ajaxWebsite + 'Home/Ytc/getAllAccount',
    type: 'GET',
    success: function (res) {
      // console.log(res)

      addToast('已完成', '用户数据已经返回来', 'notice')

      // 数组按照余额 由大到小排序
      var res = accountSort(res)

      // console.log(res)
      var html = '';
      for (var i = 0; i < res.length; i++) {
        if (i >= 20) {
          break
        }
        var account = res[i]['account']
        var number = res[i]['number']
        var freeze =  res[i]['freeze']
        var username = res[i]['username']
        var email = res[i]['email']
        console.log(res[i])
        if (number == "0") {
          number = '0.00'
        } else {
          number = new BigNumber(number)
          number = avg(number.toNumber(2), 1)
          number = number.toString()
          // console.log( typeof number)
          // console.log(number)
          if (number.indexOf(".") < 0) {
            number = number + ".00"
          }
        }
        if (freeze == "0" || freeze == null) {
          freeze = '0.00'
        } else {
          freeze = new BigNumber(freeze)
          freeze = avg(freeze.toNumber(2), 1)
          freeze = freeze.toString()
          // console.log( typeof number)
          // console.log(number)
          if (freeze.indexOf(".") < 0) {
            freeze = freeze + ".00"
          }
        }
        var addClass = 'class="update-number"'
        html +=
          "<div class='account'><img src='../static/images/avatar.png'><div><p><i class='fa fa-key' aria-hidden='true'></i><span class='account-name'> " + username + "</span></p><p><span " + addClass + ">" +
          number + " </span><span>DC</span></p>"+"<p  class='p-account'>" + account + "</p></div></div>";
      }
      // html +=
      //   '<div id="add" onclick="addAccount()"><div class="add-account"><div><i class="fa fa-plus" aria-hidden="true"></i></div><div>添加账号</div></div></div>'

      $('.all-account').append(html)
      setTimeout(function () {
        $.ajax({
          url: ajaxWebsite + 'Home/Ytc/getMainAccount',
          type: 'GET',
          // async: false,
          success: function (res) {
            var MainAccount = res
            var selectMainAccount = ".all-account p:contains('" + MainAccount + "')"
            // console.log(selectMainAccount)
            // console.log($(selectMainAccount).prev().find('span.update-number').addClass('update-this-number'))
            $(selectMainAccount).prev().find('span.update-number').addClass('update-this-number')
            $(selectMainAccount).prev().prev().prev().find('span').addClass('account-name-after')
            // 位置互换
            var main = $(selectMainAccount).parents('.account')
            var first = $('.all-account .account:eq(0)')
            main.insertBefore(first)
            setInterval(function () {
              $.ajax({
                url: ajaxWebsite + 'Home/Ytc/getAccount',
                type: 'POST',
                data: {
                  account: MainAccount
                },
                success: function (res) {
                  // console.log(res)
                  var number = new BigNumber(res)
                  var y = Math.pow(10, 18)
                  number = number.dividedBy(y)
                  number = new BigNumber(number).toFixed(2)
                  $('.update-this-number').text(number + " ")
                }
              })
            }, 3500)
          }
        })
      }, 100)




      $('.account').on('click', function () {
        var account = $(this).find('.p-account').text()
        var accountName = $(this).find('.account-name').text()
        zeroModal.loading(4);
        $.ajax({
          url: ajaxWebsite + 'Home/Ytc/getAccount',
          type: 'POST',
          data: {
            account: account
          },
          success: function (res) {
            var money = new BigNumber(res)
            var y = Math.pow(10, 18)
            money = money.dividedBy(y).toFormat()
            var setMain
            if (code == 3) {
              setMain = '<div class="o-set-main">设置为主账号</div>'
            } else {
              setMain = ''
            }
            var content = '<div class="account-detail-content"><div class="account-detail"><img src="../static/images/avatar.png" alt=""><div><p>' + accountName + '</p><p><i class="fa fa-key" aria-hidden="true"></i> <span id="a-copy" >' + account + '</span></p><p><span>' + money + '</span><span> DC</span></p></div></div><div class="account-operation"><div class="note"><p>注意</p><p>帐户不能显示传入事务，但保持和发送以太。要查看传入的事务，创建一个钱包契约来存储以太。</p></div><div class="a-opera"><div class="o-trade-from" alt="">添加到 From</div><div class="o-trade-to" alt="主帐号转账到该帐号">添加到 To</div>' + setMain + '<div class="o-copy"  alt="钱包地址复制到剪贴板">复制地址</div></div></div></div>'
            showModal("帐号详情", content, '488px', '280px', true, true, '确认', false, true)

            $('.o-trade-to').click(function () {
              $('#to').val(account)
              $('.content>div').css('display', 'none')
              $('#all-send-content').css('display', 'block')
              closeModal()
            })
            $('.o-trade-from').click(function () {
              $('#from').val(account)
              getTotalAmount(account)
              getFreezeAmount(account)
              $('.content>div').css('display', 'none')
              $('#all-send-content').css('display', 'block')
              closeModal()
            })
            $('.o-set-main').click(function () {
              console.log(account)
              changeMainAccount(account)
              closeModal()
              // ipcRenderer.send('window-reload')
            })
          }
        })

      })
      var clipboard = new Clipboard('.o-copy', {
        text: function () {
          return $('.zeromodal-container #a-copy').text()
        }
      })
      clipboard.on('success', function (e) {
        addToast("复制成功", "该帐号 钱包地址 已复制到剪切板。", "notice")
        // console.log(e);
      })
    }
  })
}

function getOneAccount(code, loginAccount, email, username) {
  $.ajax({
    url: ajaxWebsite + 'Home/Ytc/getAccount',
    type: 'POST',
    data: {
      account: loginAccount
    },
    success: function (res) {
      var money = new BigNumber(res)
      var y = Math.pow(10, 18)
      money = money.dividedBy(y).toFormat(16)
      $('.all-account').empty()

      var content = '<div class="account-detail-content" style="margin-top: 10px;"><div class="account-detail"><img src="../static/images/avatar.png" alt=""><div><p><span>' + username + '</span> <span style="font-size: 14px;">(' + email + ')</span></p><p><i class="fa fa-key" aria-hidden="true"></i><span id="a-copy"> ' + loginAccount + '</span></p><p><span>' + money + '</span><span> DC</span></p></div></div><div class="account-operation" style="margin-bottom: 20px;"><div class="note"><p>注意</p><p>帐户不能显示传入事务，但保持和发送以太。要查看传入的事务，创建一个钱包契约来存储以太。</p></div></div></div>'

      $('.all-account').append(content)
    }
  })
}


function addAccount() {
  addToast('添加账号', '功能暂未开放', 'warning')
}

function getTradeBlockDetail(string) {
  var string = string
  zeroModal.loading(4);
  $.ajax({
    url: ajaxWebsite + 'Home/Ytc/directSearchTradeDetail',
    type: 'POST',
    data: {
      string: string
    },
    success: function (res) {
      // console.log(res)
      // console.log(typeof res.value + "----" + res.value)

      var content = '<div class="trade-block-detail"><div><p>交易 Hash: </p><p>' + res.hash + '</p></div><table><tr><td>时间</td><td>' + res.add_time + '</td></tr><tr><td>数量</td><td><span>' + new BigNumber(res.value).dividedBy(Math.pow(10, 18)).toFormat() + '</span>&nbsp;<span>DC</span></td></tr><tr><td>From</td><td>' + res.from + '</td></tr><tr><td>To</td><td>' + res.to + '</td></tr>'
        // '<tr><td>交易费</td><td>' + new BigNumber(res.fee).dividedBy(Math.pow(10, 18)).toFormat() + ' DC</td></tr>'
        // + '<tr><td>Gas used</td><td>' + res.gas + '</td></tr><tr><td>Gas price</td><td>' + res.gasprice + '</td></tr>'
        +
        '<tr><td>区块</td><td><p>' + res.blocknumber + '</p><p>' + res.blockhash + '</p></td></tr></table></div>'
      showModal('交易区块信息', content, '650px', modalHeight, true, true, '确认', false, true)
    }
  })
}

function getTradeList(page, limit) {
  addToast('请稍后', '正在查询中…', 'notice')
  $.ajax({
    url: ajaxWebsite + 'Home/Ytc/getTradeList',
    type: 'POST',
    data: {
      page: page,
      limit: limit
    },
    success: function (res) {
      // alert(res)
      addToast('已完成', '交易记录数据已经返回来', 'notice')

      var content = '';
      for (var i = 0; i < res.length; i++) {
        var m = changeMonth(res[i].add_time)
        var d = changeDay(res[i].add_time)
        console.log()
        content += '<div class="record"><div><p>' + m + '</p><p>' + d + '</p></div><div><p><span>交易区块: </span><span class="trade-block">' + res[i].hash + '</span></p><span><span>From: </span><span>' + res[i].from + '</span>&nbsp;&nbsp;</span><br><span><span>To: </span><span>' + res[i].to + '</span></span></p></div><div><span>- ' + new BigNumber(res[i].value).dividedBy(Math.pow(10, 18)).toFormat() + '</span>&nbsp;<span>DC</span>&nbsp;&nbsp;<span><i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></span></div></div>'
      }
      $('.get-more').before(content)

      $('.record').click(function () {
        var string = $(this).find('.trade-block').text()
        getTradeBlockDetail(string)
      })
    },
    error: function (err) {

    }
  })
}

function changeMonth(time) {
  // console.log(time*1000)
  var t = new Date(time * 1000)
  var m = parseInt(t.getMonth()) + 1
  // console.log(typeof m)
  switch (m) {
    case 1:
      m = 'Jan'
      break
    case 2:
      m = 'Feb'
      break
    case 3:
      m = 'Mar'
      break
    case 4:
      m = 'Apr'
      break
    case 5:
      m = 'May'
      break
    case 6:
      m = 'June'
      break
    case 7:
      m = 'July'
      break
    case 8:
      m = 'Aug'
      break
    case 9:
      m = 'Sept'
      break
    case 10:
      m = 'Oct'
      break
    case 11:
      m = 'Nov'
      break
    case 12:
      m = 'Dec'
      break
  }
  // console.log(m)
  return m
}

function changeDay(time) {
  // console.log(time*1000)
  var t = new Date(time * 1000)
  var d = t.getDate()

  return d
}

function accountSort(arr) {
  var a = arr
  a.sort(function (a, b) {
    var t
    var num1 = new BigNumber(a.number)
    var num2 = new BigNumber(b.number)
    if (num2.isGreaterThanOrEqualTo(num1)) {
      t = 1
    } else if ((num1.isGreaterThan(num2))) {
      t = -1
    }
    return t
  })
  return a
}